package cn.iocoder.yudao.module.forward.service.scope;

import cn.iocoder.yudao.module.forward.dal.dataobject.scope.ScopeInfo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import org.springframework.validation.annotation.Validated;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import cn.iocoder.yudao.module.forward.controller.admin.scope.vo.*;
import cn.iocoder.yudao.module.forward.dal.dataobject.scope.ScopeDO;
import cn.iocoder.yudao.module.forward.dal.dataobject.scope.ScopeResourceDO;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;

import cn.iocoder.yudao.module.forward.dal.mysql.scope.ScopeMapper;
import cn.iocoder.yudao.module.forward.dal.mysql.scope.ScopeResourceMapper;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.module.forward.enums.ErrorCodeConstants.*;

/**
 * 授权范围 Service 实现类
 *
 * @author zhang
 */
@Service
@Validated
public class ScopeServiceImpl implements ScopeService {

    @Resource
    private ScopeMapper scopeMapper;
    @Resource
    private ScopeResourceMapper scopeResourceMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Integer createScope(ScopeSaveReqVO createReqVO) {
        // 插入
        ScopeDO scope = BeanUtils.toBean(createReqVO, ScopeDO.class);
        scopeMapper.insert(scope);

        // 插入子表
        createScopeResourceList(scope.getId(), createReqVO.getScopeResources());
        // 返回
        return scope.getId();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateScope(ScopeSaveReqVO updateReqVO) {
        // 校验存在
        validateScopeExists(updateReqVO.getId());
        // 更新
        ScopeDO updateObj = BeanUtils.toBean(updateReqVO, ScopeDO.class);
        scopeMapper.updateById(updateObj);

        // 更新子表
        updateScopeResourceList(updateReqVO.getId(), updateReqVO.getScopeResources());
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteScope(Integer id) {
        // 校验存在
        validateScopeExists(id);
        // 删除
        scopeMapper.deleteById(id);

        // 删除子表
        deleteScopeResourceByScopeId(id);
    }

    private void validateScopeExists(Integer id) {
        if (scopeMapper.selectById(id) == null) {
            throw exception(SCOPE_NOT_EXISTS);
        }
    }

    @Override
    public ScopeDO getScope(Integer id) {
        return scopeMapper.selectById(id);
    }

    @Override
    public PageResult<ScopeDO> getScopePage(ScopePageReqVO pageReqVO) {
        return scopeMapper.selectPage(pageReqVO);
    }

    // ==================== 子表（授权范围信源关联） ====================

    @Override
    public List<ScopeResourceDO> getScopeResourceListByScopeId(Integer scopeId) {
        return scopeResourceMapper.selectListByScopeId(scopeId);
    }

    @Override
    public List<ScopeDO> getScopeByGroupId(Integer groupId) {
        return scopeMapper.selectList("group_id",groupId);
    }

    @Override
    public List<ScopeInfo> selectBySourceId(Integer sourceId, String topicType){
        QueryWrapper<ScopeInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("fsr.resource_id", sourceId);
        queryWrapper.eq("fsr.deleted", 0);
        queryWrapper.eq("fs.topic_type", topicType);
        return scopeResourceMapper.selectScopeInfos(queryWrapper);
    }

    private void createScopeResourceList(Integer scopeId, List<ScopeResourceDO> list) {
        list.forEach(o -> o.setScopeId(scopeId));
        scopeResourceMapper.insertBatch(list);
    }

    private void updateScopeResourceList(Integer scopeId, List<ScopeResourceDO> list) {
        deleteScopeResourceByScopeId(scopeId);
		list.forEach(o -> o.setId(null).setUpdater(null).setUpdateTime(null)); // 解决更新情况下：1）id 冲突；2）updateTime 不更新
        createScopeResourceList(scopeId, list);
    }

    private void deleteScopeResourceByScopeId(Integer scopeId) {
        scopeResourceMapper.deleteByScopeId(scopeId);
    }

}